package com.hhq.core;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Map;
import java.util.TreeMap;

/**
 * 封装响应的类
 */
public class Res {

    public String version = "HTTP/1.1";
    public int code = 200;             // 返回值，200，404等
    public String desc = "OK";          
    public Map<String, String> headers = new TreeMap<>();  // 响应头，Content-Type等
    public String body = "";                           // 字符串主体，例如 {"name": "hhq", "pwd": "123"}
    public byte[] bboby = null;                        // 字节流主体，可以是图片等文件

    // 将响应对象转为字节流，准备传输
    public byte[] toBytes() {
        // bao 存储身体字节流
        ByteArrayOutputStream bao = new ByteArrayOutputStream();
        ByteArrayOutputStream all = new ByteArrayOutputStream();
        int content_length = 0;  // 内容长度
        try {
            byte[] body_1 = body.getBytes("UTF-8");
            content_length += body_1.length;
            bao.write(body_1);
            if( bboby !=null){
                content_length += bboby.length;
                bao.write(bboby);
            }
            this.headers.put("Content-Length", content_length+"");

            StringBuffer sb = new StringBuffer();
            sb.append(version);
            sb.append(" ");
            sb.append(code + " ");
            sb.append(desc + "\r\n");
            for (Map.Entry<String, String> entry : this.headers.entrySet()) {
                sb.append(entry.getKey() + ":");
                sb.append(entry.getValue() + "\r\n");
            }
            sb.append("\r\n");

            all.write(sb.toString().getBytes("UTF-8"));
            all.write(bao.toByteArray());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return all.toByteArray();
    }

    @Override
    public String toString(){
        StringBuffer sb = new StringBuffer();
        sb.append(version);
        sb.append(" ");
        sb.append(code + " ");
        sb.append(desc+"\r\n");
        for( Map.Entry<String ,String> entry : headers.entrySet() ){
            sb.append(entry.getKey() + ":");
            sb.append(entry.getValue() + "\r\n");
        }
        sb.append( "\r\n");
        sb.append(body+"\n");
        return sb.toString();
    }
}